﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class InterfaceImplementationRule : ILRule<InterfaceImplementationHandle>
    {
        [ILInfo(true, ILInfoParseMethod.AsEntityHandle)]
        public TypeDefinitionHandle Type { get; }

        [ILInfo(true)]
        public EntityHandle ImplementedInterface { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public InterfaceImplementationRule(
            TypeDefinitionHandle type,
            EntityHandle implementedInterface)
            : base()
        {
            Type = type;
            ImplementedInterface = implementedInterface;
        }

        public InterfaceImplementationRule(MetadataReader reader, InterfaceImplementationHandle interfaceImplementationHandle)
            : base(reader)
        {
            InterfaceImplementation interfaceImplementation = reader.GetInterfaceImplementation(interfaceImplementationHandle);
            ImplementedInterface = interfaceImplementation.Interface;
            CustomAttributes = interfaceImplementation.GetCustomAttributes();
        }

        public override InterfaceImplementationHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddInterfaceImplementation(
                type: Type,
                implementedInterface: ImplementedInterface);
        }
    }
}